package com.superiron.scaffold.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.superiron.scaffold.core.exception.Asserts;
import com.superiron.scaffold.security.service.GlobalUserDetailsService;
import com.superiron.scaffold.security.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 后台用户管理Service实现类
 * Created by macro on 2018/4/26.
 */
@Service
@Slf4j
public class LoginServiceImpl {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;
	
	@Autowired
	private GlobalUserDetailsService globalUserDetailsService;
	
	public String login(String username, String password) {
		String token = null;
		//密码需要客户端加密后传递
		try {
			UserDetails userDetails = globalUserDetailsService.loadUserByUsername(username);
			if(!passwordEncoder.matches(password,userDetails.getPassword())){
				Asserts.fail("密码不正确");
			}
			if(!userDetails.isEnabled()){
				Asserts.fail("帐号已被禁用");
			}
			UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
			SecurityContextHolder.getContext().setAuthentication(authentication);
			token = jwtTokenUtil.generateToken(userDetails);
		} catch (AuthenticationException e) {
			log.warn("登录异常:{}", e.getMessage());
		}
		return token;
	}
	
}
